package com.haiqiu.system.service.impl;

import com.haiqiu.common.exception.BaseException;
import com.haiqiu.common.page.PageRequest;
import com.haiqiu.common.page.PageResponse;
import com.haiqiu.common.result.Constants;
import com.haiqiu.common.utils.tools.StringUtil;
import com.haiqiu.system.entity.SysRole;
import com.haiqiu.system.entity.SysUser;
import com.haiqiu.system.entity.dto.SysRoleDto;
import com.haiqiu.system.entity.query.UserQuery;
import com.haiqiu.system.entity.vo.SysRoleVo;
import com.haiqiu.system.mapper.SysRoleMapper;
import com.haiqiu.system.mapper.SysUserMapper;
import com.haiqiu.system.service.SysRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author: HaiQiu
 * @Date: 2021/4/6
 * @Description: 角色逻辑层
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPermissionServiceImpl permissionService;


    /**
     * 根据ID删除数据
     *
     * @param id 数据ID
     */
    @Override
    public void deleteByPrimaryKey(Long id) {
        if (StringUtils.isEmpty(id)) {
            throw new BaseException(Constants.ID_EXITS);
        }
        if (sysRoleMapper.deleteByPrimaryKey(id) == 0) {
            throw new BaseException(Constants.FAIL_DEL);
        }
    }


    /**
     * 新增
     *
     * @param roleDto 角色实体
     */
    @Override
    public void save(SysRoleDto roleDto) {
        SysRole sysRole = checkAddData(roleDto);
        sysRole.setActive(Constants.ON);
        sysRole.setDel(false);
        Date date = new Date();
        sysRole.setCreateTime(date);
        sysRole.setUpdateTime(date);
        if (sysRoleMapper.insert(sysRole) == 0) {
            throw new BaseException(Constants.FAIL_ADD);
        }
        if (roleDto.getMenuIds() != null && roleDto.getMenuIds().size() != 0) {
            if (sysRoleMapper.insertByPermissionIds(sysRole.getId(), roleDto.getMenuIds()) == 0) {
                throw new BaseException("添加关联权限失败，请稍后再试！");
            }
        }
        permissionService.delRedisAuthList();
    }

    /**
     * 检查数据
     *
     * @param roleDto 角色实体
     * @return 返回检验后的实体
     */
    private SysRole checkAddData(SysRoleDto roleDto) {
        if (StringUtils.isEmpty(roleDto)) {
            throw new BaseException("无效数据");
        }
        if (StringUtils.isEmpty(roleDto.getMenuIds())) {
            throw new BaseException("未选中权限");
        }
        if (StringUtils.isEmpty(roleDto.getName())) {
            throw new BaseException("无效角色名称");
        }
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(roleDto, sysRole);
        return sysRole;
    }


    /**
     * 根据ID查询
     *
     * @param id 数据ID
     * @return 角色实体
     */
    @Override
    public SysRoleVo get(Long id) {
        SysRole sysRole = sysRoleMapper.selectByPrimaryKey(id);
        if (sysRole == null) {
            throw new BaseException(Constants.DATA_EXIT);
        }
        SysRoleVo roleVo = new SysRoleVo();
        BeanUtils.copyProperties(sysRole, roleVo);
        //获取角色的权限集合
//        List<SysPermission> sysPermissions = sysRoleMapper.selectAuthByRoleId(roleVo.getId());
//        roleVo.setPermissionList(sysPermissions);
        return roleVo;
    }


    /**
     * 修改角色
     *
     * @param roleDto 角色实体
     */
    @Override
    public void update(SysRoleDto roleDto) {
        //检查数据
        SysRole sysRole = checkAddData(roleDto);
        //根据角色ID删除对应的权限
        this.delByRoleIdForAuth(sysRole.getId());
        //根据角色ID添加对应的权限
        this.addByRoleIdForAuth(roleDto);
        if (sysRoleMapper.updateByPrimaryKeySelective(roleDto) == 0) {
            throw new BaseException(Constants.FAIL_UPDATE);
        }
        permissionService.delRedisAuthList();
    }


    /**
     * 根据角色ID删除对应的权限
     *
     * @param roleId 角色ID
     */
    public void delByRoleIdForAuth(Long roleId) {
        if (sysRoleMapper.delAuthByRoleId(roleId) == 0) {
            System.out.println("角色没有权限，无法删除");
//            throw new BaseException("删除角色的绑定权限失败");
        }
    }

    /**
     * 根据角色ID添加对应的权限
     *
     * @param roleDto 角色实体包含权限集合
     */
    public void addByRoleIdForAuth(SysRoleDto roleDto) {
        if (roleDto.getMenuIds() != null && roleDto.getMenuIds().size() != 0) {
            if (sysRoleMapper.insertByPermissionIds(roleDto.getId(), roleDto.getMenuIds()) == 0) {
                throw new BaseException("添加关联权限失败，请稍后再试！");
            }
        }
    }

    /**
     * 批量删除角色
     *
     * @param ids 数据ID集合
     * @return 成功条数
     */
    @Override
    public int delete(Set<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BaseException(Constants.ID_EXITS);
        }
        int i = sysRoleMapper.delBatch(ids);
        if (i == 0) {
            throw new BaseException(Constants.FAIL_DEL);
        }
        for (Long id : ids) {
            sysRoleMapper.delAuthByRoleId(id);
            sysRoleMapper.delUserByRoleId(id);
        }
        permissionService.delRedisAuthList();
        return i;
    }


    /**
     * 分页模糊查询
     *
     * @param request 查询实体（包含分页）
     * @return 返回分页数据
     */
    @Override
    public PageResponse<SysRole> list(PageRequest<SysRole> request) {
        SysRole sysRole = StringUtil.checkObjFieldIsNull(request.getParams());
        long count = sysRoleMapper.count(sysRole);
        PageResponse<SysRole> response = new PageResponse<>();
        response.setPageSize(request.getPageSize());
        response.setTotal(count);
        response.setPageIndex(request.getPageIndex());
        if (count > 0) {
            List<SysRole> list = sysRoleMapper.list(sysRole, request.getOffset(), request.getPageSize());
            response.setData(list);
        }
        return response;
    }


    /**
     * 查询所有角色
     *
     * @return 返回所有角色实体
     */
    @Override
    public List<SysRole> all() {
        return sysRoleMapper.all();
    }


    @Override
    public int active(List<SysRoleDto> roleDtos) {
        int i = 0;
        for (SysRoleDto roleDto : roleDtos) {
            SysRole sysRole = new SysRole();
            sysRole.setActive(roleDto.getActive());
            sysRole.setId(roleDto.getId());
            sysRoleMapper.updateByPrimaryKeySelective(sysRole);
            i++;
        }
        return i;
    }

    @Override
    public Map<String, Object> allocatedList(Long roleId, Long pageIndex, Long pageSize, String username, String phone, String email) {
        long count = sysRoleMapper.allocatedCount(roleId, username, phone, email);
        Map<String, Object> map = new HashMap<>(6);
        map.put("total", count);
        if (count > 0) {
            List<SysUser> sysUserList = sysRoleMapper.allocatedPage(roleId, pageIndex, pageSize, username, phone, email);
            map.put("rows", sysUserList);
        } else {
            map.put("rows", null);
        }
        return map;
    }

    @Override
    public Map<String, Object> unallocatedList(Long roleId, Long pageIndex, Long pageSize, String username, String phone, String email) {
        long count = sysRoleMapper.unallocatedCount(roleId, username, phone, email);
        Map<String, Object> map = new HashMap<>(6);
        map.put("total", count);
        if (count > 0) {
            List<SysUser> sysUserList = sysRoleMapper.unallocatedPage(roleId, pageIndex, pageSize, username, phone, email);
            map.put("rows", sysUserList);
        } else {
            map.put("rows", null);
        }
        return map;
    }

    @Override
    public int authorize(UserQuery userQuery) {
        if (userQuery.getRoleId()==null || CollectionUtils.isEmpty(userQuery.getUserIds()) || userQuery.getActive()==null){
            throw new BaseException("参数不全，请查验接口参数");
        }
        int success = 0;
        if (userQuery.getActive()){
            // 批量激活
            success = sysRoleMapper.addUserByRoleId(userQuery.getRoleId(), userQuery.getUserIds());
        }else {
            // 批量删除
            success =  sysRoleMapper.deleteUserByRoleId(userQuery.getRoleId(), userQuery.getUserIds());
        }
        return success;
    }
}
